package com.originskyseed.platform.common.web.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.api.constant.WebappKeyConstants;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.config.FilterConfig;
import com.originskyseed.platform.core.filter.util.FilterSharedSessionUtil;
import com.originskyseed.platform.core.filter.util.FilterSystemTypeUtil;
import com.originskyseed.platform.core.filter.util.FilterTokenLockUtil;
import com.originskyseed.platform.core.filter.util.FilterTokenUtil;
import com.originskyseed.platform.core.filter.vo.SingleSignOnToken;
import com.originskyseed.platform.core.redis.util.RedisUtil;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;

/**
 * 系统Controller类
 * 
 * @author LiangMingHui
 *
 */
@Controller
@RequestMapping("/system")
public class SystemController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SystemController.class);

	/**
	 * 获取时间戳
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getTimestamp.jsonx", method = { RequestMethod.POST, RequestMethod.GET })
	public BaseResponseBody<Long> getTimestamp(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody<Long> result = null;
		try {
			result = new BaseResponseBody<Long>(true, CommonResponseCode.SUCCESS.getCode(), null, System.currentTimeMillis());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Long>(false, CommonResponseCode.ERROR.getCode(), null, e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 获取会话ID
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSessionId.jsonx", method = { RequestMethod.POST, RequestMethod.GET })
	public BaseResponseBody<String> getSessionId(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody<String> result = null;
		try {
			result = new BaseResponseBody<String>(true, CommonResponseCode.SUCCESS.getCode(), null, request.getSession().getId());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<String>(false, CommonResponseCode.ERROR.getCode(), null, e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 获取系统配置
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSystemConfig.jsonx", method = { RequestMethod.POST, RequestMethod.GET })
	public BaseResponseBody<Map<String, Object>> getSystemConfig(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody<Map<String, Object>> result = null;
		try {
			Map<String, Object> systemConfig = new HashMap<String, Object>();

			// 获取客户端系统类型
			String clientSystemType = FilterSystemTypeUtil.getInstance().getClientSystemType(request, response);

			// 获取token配置
			FilterConfig tokenConfig = FilterTokenUtil.getInstance().getFilterConfig(clientSystemType);
			if (null != tokenConfig) {
				systemConfig.put(WebappKeyConstants.TOKEN_NAME_KEY, tokenConfig.getSingleSignOnTokenCookieName());
				systemConfig.put(WebappKeyConstants.TOKEN_EXPIRES_KEY, tokenConfig.getSingleSignOnTokenCookieExpiresInterval());
			}

			// 获取共享session配置
			FilterConfig sharedSessionConfig = FilterSharedSessionUtil.getInstance().getFilterConfig(clientSystemType);
			if (null != sharedSessionConfig) {
				systemConfig.put(WebappKeyConstants.SESSIONID_NAME_KEY, sharedSessionConfig.getSharedSessionCookieName());
				systemConfig.put(WebappKeyConstants.SESSIONID_EXPIRES_KEY, sharedSessionConfig.getSharedSessionCookieExpiresInterval());
			}

			result = new BaseResponseBody<Map<String, Object>>(true, CommonResponseCode.SUCCESS.getCode(), null, systemConfig);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Map<String, Object>>(false, CommonResponseCode.ERROR.getCode(), null, e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 验证登录凭证
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/validateToken.jsonx", method = { RequestMethod.POST, RequestMethod.GET })
	public BaseResponseBody<Integer> validateToken(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody<Integer> result = null;
		try {
			Integer responseCode = CommonResponseCode.FAILURE_AUTHENTICATION.getCode();

			// 获取客户端系统类型
			String clientSystemType = FilterSystemTypeUtil.getInstance().getClientSystemType(request, response);

			// 获取token配置
			FilterConfig tokenConfig = FilterTokenUtil.getInstance().getFilterConfig(clientSystemType);
			if (null != tokenConfig) {

				// 获取客户端凭证
				String clientTokenId = FilterTokenUtil.getInstance().getClientToken(request, response, tokenConfig);
				if (StringUtils.isNotBlank(clientTokenId)) {

					// 获取服务端凭证
					SingleSignOnToken serverSSOToken = FilterTokenUtil.getInstance().getServerToken(clientTokenId, tokenConfig);
					if (null != serverSSOToken) {

						// 校验服务端凭证锁
						if (FilterTokenLockUtil.getInstance().checkServerTokenLock(serverSSOToken, tokenConfig)) {

							// 校验服务端凭证
							if (FilterTokenUtil.getInstance().checkServerToken(serverSSOToken, tokenConfig)) {
								responseCode = CommonResponseCode.SUCCESS_AUTHENTICATION.getCode();
							} else {
								responseCode = CommonResponseCode.FAILURE_EXPIRED_AUTHENTICATION.getCode();
							}

						} else {
							responseCode = CommonResponseCode.FAILURE_LOCKED_AUTHENTICATION.getCode();
						}

					} else {
						responseCode = CommonResponseCode.FAILURE_EXPIRED_AUTHENTICATION.getCode();
					}

				} else {
					responseCode = CommonResponseCode.FAILURE_EXPIRED_AUTHENTICATION.getCode();
				}

			}

			result = new BaseResponseBody<Integer>(true, CommonResponseCode.SUCCESS.getCode(), null, responseCode);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Integer>(false, CommonResponseCode.ERROR.getCode(), null, e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 获取活跃登录凭证数
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getActiveTokensNumber.jsonx", method = { RequestMethod.POST, RequestMethod.GET })
	public BaseResponseBody<Long> getActiveTokensNumber(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody<Long> result = null;
		try {
			Long count = 0L;

			// 请求参数
			Long recentTimeInterval = this.getParameterLong("recentTimeInterval", 60000L);

			// 获取客户端系统类型
			String clientSystemType = FilterSystemTypeUtil.getInstance().getClientSystemType(request, response);

			// 获取token配置
			FilterConfig tokenConfig = FilterTokenUtil.getInstance().getFilterConfig(clientSystemType);
			if (null != tokenConfig) {

				// 获取服务端租户标识
				String tenantCode = TenantCodeUtil.getInstance().getServerTenantCode();

				// 构建Token标识
				StringBuilder tokenId = new StringBuilder();
				if (StringUtils.isNotBlank(tenantCode)) {
					tokenId.append(tenantCode).append(":");
				}
				tokenId.append("*");

				Set<String> tokenKeySet = FilterTokenUtil.getInstance().getServerTokenKeySet(tokenId.toString(), tokenConfig);
				for (String tokenKey : tokenKeySet) {

					// 判断Token时间戳
					SingleSignOnToken ssoToken = RedisUtil.getInstance().getForObject(tokenKey, SingleSignOnToken.class);
					if (null != ssoToken.getCreateDate() && System.currentTimeMillis() - ssoToken.getCreateDate() <= recentTimeInterval) {
						count++;
					} else if (null != ssoToken.getUpdateDate() && System.currentTimeMillis() - ssoToken.getUpdateDate() <= recentTimeInterval) {
						count++;
					}

				}

			}

			result = new BaseResponseBody<Long>(true, CommonResponseCode.SUCCESS.getCode(), null, count);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Long>(false, CommonResponseCode.ERROR.getCode(), null, e.getMessage(), null);
		}
		return result;
	}

}
